package com.yc.sole.financial.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.common.domain.StateCountResp;
import com.yc.sole.financial.dto.ReceiptDto;
import com.yc.sole.financial.entity.Receipt;
import com.yc.sole.financial.mapper.ReceiptMapper;
import com.yc.sole.financial.request.ReceiptQueryReq;
import com.yc.sole.financial.response.ReceiptResp;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2024-03-08
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ReceiptRepository extends ServiceImpl<ReceiptMapper, Receipt> {

    /**
     * 新增
     *
     * @param receiptDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveReceipt(ReceiptDto receiptDto) {
        Receipt entity = new Receipt();
        BeanUtil.copyProperties(receiptDto, entity);
        this.save(entity);
    }

    /**
     * 通过Id修改
     *
     * @param receiptDto
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateReceiptById(ReceiptDto receiptDto) {
        Receipt entity = new Receipt();
        BeanUtil.copyProperties(receiptDto, entity);
        this.updateById(entity);
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return RestResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteReceiptByIds(Collection<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 根据id获取
     *
     * @param ids
     * @return RestResult
     */
    public List<ReceiptDto> selectReceiptByIds(Set<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(this.listByIds(ids), ReceiptDto.class);
    }

    /**
     * 根据id获取
     *
     * @param id
     * @return RestResult
     */
    public ReceiptDto selectReceiptById(Long id) {
        return BeanUtil.copyProperties(this.getById(id), ReceiptDto.class);
    }

    /**
     * 根据id获取详情
     *
     * @param id
     * @return RestResult
     */
    public ReceiptResp selectReceiptDetailById(Long id) {
        return this.baseMapper.selectReceiptById(id);
    }

    /**
     * 分页查询
     *
     * @param page
     * @return RestResult
     */
    public Paging<ReceiptResp> selectReceiptPage(Paging page, ReceiptQueryReq queryReq) {
        return PageUtil.pageCopy(this.baseMapper.selectReceiptPage(PageUtil.toMybatisPage(page), queryReq), ReceiptResp.class);
    }

    /**
     * 查询收款方式数量
     *
     * @param queryReq
     * @return
     */
    public List<StateCountResp> selectReceiptMethodCount(ReceiptQueryReq queryReq) {
        return this.baseMapper.selectReceiptMethodCount(queryReq);
    }

    private LambdaQueryWrapper<Receipt> getWrapper(ReceiptQueryReq queryReq) {
        LambdaQueryWrapper<Receipt> wrapper = Wrappers.<Receipt>lambdaQuery()
                .eq(Objects.nonNull(queryReq.getCustomerId()), Receipt::getCustomerId, queryReq.getCustomerId())
                .eq(Objects.nonNull(queryReq.getReceiptMethod()), Receipt::getReceiptMethod, queryReq.getReceiptMethod())
                .like(CharSequenceUtil.isNotBlank(queryReq.getReceiptNo()), Receipt::getReceiptNo, queryReq.getReceiptNo())
                .like(CharSequenceUtil.isNotBlank(queryReq.getOrderNo()), Receipt::getOrderNo, queryReq.getOrderNo())
                .orderByDesc(Receipt::getId);
        if (CollUtil.isNotEmpty(queryReq.getReceiptDateRange())
                && CharSequenceUtil.isNotBlank(queryReq.getReceiptDateRange().get(0))
                && CharSequenceUtil.isNotBlank(queryReq.getReceiptDateRange().get(1))) {
            wrapper.between(Receipt::getReceiptDate, queryReq.getReceiptDateRange().get(0), queryReq.getReceiptDateRange().get(1));
        }
        return wrapper;
    }

    /**
     * 查询客户已收款金额
     *
     * @return
     */
    public Map<Long, BigDecimal> selectCustomerReceiptAmount(Collection<Long> customerIds) {
        LambdaQueryWrapper<Receipt> wrapper = Wrappers.<Receipt>lambdaQuery()
                .select(Receipt::getCustomerId, Receipt::getAmount)
                .in(Receipt::getCustomerId, customerIds);
        return this.list(wrapper).stream().collect(Collectors.groupingBy(Receipt::getCustomerId, Collectors.reducing(BigDecimal.ZERO, Receipt::getAmount, BigDecimal::add)));
    }
}
